const express = require("express");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.Implement.findAll({ include: ["Project", "technician", "implementor"] })
    .then((implements) => res.send(implements))
    .catch((err) => {
      res.send(err);
    });
});

router.get("/get_by_id", verify, (req, res) => {
  db.Implement.findOne({
    where: {
      id: req.query.id,
    },
  })
    .then((implement) => {
      res.send(implement);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.get("/to_be_censored", verify, (req, res) => {
  // console.log('hi');
  // console.log(req.query);
  const checkerId = req.query.checkerId;
  const status = req.query.status;
  db.Implement.findAll({
    where: {
      checker_id: checkerId,
      approval_status: status,
    },
    include: ["Project", "technician", "implementor"],
  })
    .then((implements) => {
      res.send(implements);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.post("/add", verify, (req, res) => {
  const implement = req.body;
  console.log(implement);
  db.Implement.create(implement)
    .then((implement) => {
      res.send(implement);
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/delete", verify, (req, res) => {
  db.Implement.destroy({
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ deleted: n });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/edit", verify, (req, res) => {
  db.Implement.update(req.body, {
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ updated: n });
    })
    .catch((err) => {
      res.send(err);
    });
});
module.exports = router;
